import re
import logging
from os import path
from utils import file_util


# 占位符正则表达式
phPattern = r'@{.*}'

# 示例注解正则表达式，这里都是支持跨行的
eXmlPattern = r'<!--@(?:.|\n)*?-->'
eShPattern = r'#@(?:.|\n)*?@#'


# 文件创建器，生成单个文件
class FileCreator:
    encoding = 'utf-8'
    examplePattern: str = None
    lineSep = '\n'
    importDir: str
    exportDir: str
    content: str
    data: {}

    def __init__(self, importDir: str, exportDir: str):
        self.importDir = importDir
        self.exportDir = exportDir
        self.data = {}

    # 返回处理的文件名
    def getFileName(self):
        return ''

    # 创建替换用的数据
    def initData(self):
        pass

    def readFile(self):
        self.content = file_util.read_text_file(self.getImportPathFile(), self.encoding)

    def writeFile(self):
        file_util.write_text_file(self.content, self.getExportPathFile())

    # 删除示例注释
    def removeExamples(self):
        if not self.examplePattern:
            return

        try:
            phs = re.findall(self.examplePattern, self.content)
            for ph in phs:
                # logging.warning('%s => %s' % (self.getFileName(), ph))
                self.content = self.content.replace(ph, '')
        except Exception as ex:
            logging.error(str(ex))

    # @{xxx} 取出其中的值 xxx
    @staticmethod
    def getPhKey(ph: str):
        return ph[2:len(ph) - 1]

    # 获取导出文件路径
    def getImportPathFile(self) -> str:
        return path.join(self.importDir, self.getFileName())

    # 获取模版文件路径
    def getExportPathFile(self) -> str:
        return path.join(self.exportDir, self.getFileName())

    # 文件替换处理
    def process(self):
        ph = ''
        try:
            self.initData()

            # 查找所有占位符
            phs = re.findall(phPattern, self.content)
            if not phs:
                return

            logging.debug('%s => keys: %s' % (self.getFileName(), phs))

            # 替换占位符
            for ph in phs:
                key = self.getPhKey(ph)
                value = self.data.get(key)

                if not value:
                    logging.warning('%s => %s: 没有对应值！' % (self.getFileName(), key))
                    value = ''

                self.content = self.content.replace(ph, value)
        except Exception as ex:
            logging.error('%s => %s: %s' % (self.getFileName(), ph, str(ex)))

        # 替换示例注释
        self.removeExamples()

    # 处理文件
    def generate(self):
        self.readFile()
        self.process()
        self.writeFile()


# 文件管理器，管理一组配置文件
class FileManager:
    # 模版文件目录
    importDir: str

    # 生成文件目录
    exportDir: str
    creators = []

    def __init__(self, importDir: str, exportDir: str):
        self.importDir = importDir
        self.exportDir = exportDir
        self.init()

    def init(self):
        pass

    # 导出文件
    def generate(self) -> int:
        file_util.create_dir_tree(self.exportDir)

        error_count = 0
        for creator in self.creators:
            try:
                creator.generate()
            except Exception as ex:
                error_count += 1
                logging.error(creator.getFileName() + " => ", ex)

        return error_count
